package com.edee.bigday.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edee.bigday.ware.service.WareSkuService;
import com.edee.bigday.ware.vo.MergeVo;
import com.edee.bigday.ware.dao.PurchaseDao;
import com.edee.bigday.ware.entity.PurchaseDetailEntity;
import com.edee.bigday.ware.entity.PurchaseEntity;
import com.edee.bigday.ware.service.PurchaseDetailService;
import com.edee.bigday.ware.service.PurchaseService;
import com.edee.bigday.ware.vo.PurchaseDoneItemsVo;
import com.edee.bigday.ware.vo.PurchaseDoneVo;
import com.edee.common.constant.WareConstant;
import com.edee.common.utils.PageUtils;
import com.edee.common.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        String status = (String)params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("status",status);
        }
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(wrapper->{
                wrapper.eq("id" ,key).or().eq("assignee_id",key).or().like("assignee_name",key);
            });
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivedPurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    /**
     * 合并整单
     *
     * @param mergeVo
     */
    @Transactional
    @Override
    public void mergePuchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            //如果没有选择采购单，则新建一个采购单：
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //TODO 确认采购单状态为0或1时，才可以合并整单。
        //2021.01.29 10:08 优化完成。by edee.
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(itemId -> {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(itemId);
            return purchaseDetailEntity;
        }).filter(detailEntity -> {
            Integer status = detailEntity.getStatus();
            return (status == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode() || status == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
        }).map(detailEntity -> {
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        //更新之后，设置更新时间：
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * 领取采购单的业务处理
     *
     * @param ids 采购单的id
     */
    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单的状态是"新建"或者"已分配"：
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> {
            Integer status = item.getStatus();
            /*if (status == WareConstant.PurchaseStatusEnum.CREATED.getCode() || status == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;*/
            return status == WareConstant.PurchaseStatusEnum.CREATED.getCode() || status == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2、改变采购单的状态：
        this.updateBatchById(collect);
        //3、改变采购项的状态：
        collect.forEach(item -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailsByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntities = purchaseDetailEntities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntities);
        });
    }

    /**
     * 开启事务
     *
     * @param doneVo
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        //1、根据采购结果改变采购项(即采购需求)的状态：
        List<PurchaseDoneItemsVo> items = doneVo.getItems();
        //采购成败标识：
        Boolean flag = true;
        List<PurchaseDetailEntity> toUpdateDetails = new ArrayList<>();
        for (PurchaseDoneItemsVo item : items) {
            Integer status = item.getStatus();
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setStatus(status);
            detailEntity.setId(item.getItemId());
            //收集等待更新的采购项：
            toUpdateDetails.add(detailEntity);
            if (status == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
            } else {
                //2、将完成的采购项进行入库操作：
                PurchaseDetailEntity detailById = purchaseDetailService.getById(item.getItemId());
                //上面的item.getItemId()一度错写为doneVo.getId()
                wareSkuService.addStock(detailById.getSkuId(), detailById.getWareId(), detailById.getSkuNum());
            }
            //flag = !(status==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            //上面使用!，不利于快速运算。
        }
        purchaseDetailService.updateBatchById(toUpdateDetails);

        //3、根据采购项的结果改变采购单的状态：
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISHED.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}